import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let lifeData = {};

try {
  // 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
  lifeData = uni.getStorageSync('lifeData');
} catch (e) {

}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = [];

// 保存变量到本地存储中
const saveLifeData = function (key, value) {
  if (saveStateKeys.indexOf(key) != -1) {
    let tmp = uni.getStorageSync('lifeData');
    tmp = tmp ? tmp : {};
    tmp[key] = value;
    uni.setStorageSync('lifeData', tmp);
  }
}

const state = {
  // 用户信息
  // vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {},
}

const mutations = {
  $uStore(state, payload) {
    let nameArr = payload.name.split('.');
    let saveKey = '';
    let len = nameArr.length;
    if (nameArr.length >= 2) {
      let obj = state[nameArr[0]];
      for (let i = 1; i < len - 1; i++) {
        obj = obj[nameArr[i]];
      }
      obj[nameArr[len - 1]] = payload.value;
      saveKey = nameArr[0];
    } else {
      state[payload.name] = payload.value;
      saveKey = payload.name;
    }
    // 保存变量到本地
    saveLifeData(saveKey, state[saveKey])
  }
}


const store = new Vuex.Store({
  state,
  mutations,
})

export default store